/**
 * base64  to blob二进制
 */
export const dataURItoBlob = (dataURI) => {
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
  var byteString = atob(dataURI.split(',')[1]); //base64 解码
  var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
  var intArray = new Uint8Array(arrayBuffer); //创建视图
  for (var i = 0; i < byteString.length; i++) {
    intArray[i] = byteString.charCodeAt(i);
  }
  return new Blob([intArray], {
    type: mimeString
  });
}
/**
 * 
 * blob二进制 to base64
 **/
export const blobToDataURI = (blob, callback) => {
  var reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = function(e) {
    callback(e.target.result);
  }
}
/**
 * 
 * file文件转换为base64
 **/
export const fileToBase64 = (blob) => {
  return new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function() {
      const res = reader.result.split(";base64,")[1]
      resolve(res)
    };
  })
}
export const dataURLtoFile = (dataurl, filename) => {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}
export const imageCompress = (file) => {
  return new Promise((resolve, reject) => {
    //压缩转化为base64
    var reader = new FileReader(); //读取文件的对象
    reader.readAsDataURL(file);
    reader.onload = function(e) {
      //读取完成的钩子
      const img = new Image();
      const quality = 3000000 / file.size; // 图像质量
      const canvas = document.createElement('canvas');
      const drawer = canvas.getContext('2d');
      img.src = this.result;
      //图片压缩转码
      img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
        let base64 = canvas.toDataURL(file.type, quality);
        resolve(dataURLtoFile(base64, file.name))
      };
    };
  });
};
export const calcImgs = (src) => new Promise((resolve, reject) => {
  if (!src) {
    reject('图片加载失败，请检查url是否正确');
  }
  var img = new Image();
  img.src = src;
  img.onerror = () => {
    reject('图片加载失败，请检查url是否正确');
    return;
  };
  img.onload = () => {
    let imgW = img.width;
    let imgH = img.height;
    scale = imgW / imgH;
    w = imgW / w;
    h = imgH / scale;
    //生成canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    resolve({
      width: imgW,
      height: imgH,
    });
    img = img.onload = img.onerror = null;
  };
});
